home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++,rb.technical
- Subject: Re: Can copy constructor and operator= share code?
- Followup-To: comp.lang.c++,rb.technical
- Date: 5 Mar 1996 13:24:21 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Message-ID: <4hhfa5$m6r@dawn.mmm.com>
- References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <VA.00000053.00cdab05@fred> <4hdkdj$3id0@news-s01.ny.us.ibm.net>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- rwolf@ibm.net wrote:
- > In <VA.00000053.00cdab05@fred>, Frederic LACHASSE
- > <lachass@worldnet.fr> writes:
- > >In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com
- > >(Boris Burtin) wrote:
- > >>
- > >> I have noticed that a copy constructor and operator= perform pretty
- > >> much the same function. The code I wrote for my class simply copies
- > >> each member variable from one class to the other.
- > >>
-
- > A rather typical form is to have the create a "ShallowCopy"
- > function that is called from both the copy constructor and the
- > operator=. ShallowCopy copies only the member variables
- > at the current derivation level.
-
- > T::T(const T& t)
- > {
- > ShallowCopy(t);
- > }
-
- > T& operator=(const T& t )
- > {
- > if (&t!=this)
- > {
- > ClassReset(); // direct destructor calls are bad form
- > ShallowCopy(t);
- > parentclass::operator=(t);
-
- > }
- > return *this;
- > }
-
-
- > If this form is followed at each level of derivation it will do what
- > you want.
-
- The ShallowCopy function is not implemented here, but if it functions
- as the name implies, a member which points to dynamically allocated
- data would be copied by copying the pointer itself, not by creating a
- new copy of the original pointed-to data. This creates a problem with
- multiple deletion and dangling pointers as one of the copies is destroyed.
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-